package cn.xing.managementSystem.controller;

import cn.xing.managementSystem.bean.ResponseContent;
import cn.xing.managementSystem.domain.RollingImage;
import cn.xing.managementSystem.service.RollingImageService;
import cn.xing.managementSystem.utils.Preconditions;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author cuixing
 * @package cn.xing.managementSystem.controller
 * @class RollingImageController
 * @email xing.cui@magicwindow.cn
 * @date 2018/4/24 下午11:27
 * @description
 */
@Controller
public class RollingImageController {

    @Autowired
    private RollingImageService rollingImageService;

    @Value("${image.url}")
    private String imageUrl;


    @RequestMapping("/rollingImageList")
    public ModelAndView rollingImageList(){
        List<RollingImage> rollingImages = rollingImageService.getRollingImageList();
        ModelAndView mv = new ModelAndView("content/rollingImageList");
        mv.addObject("rollingImages", rollingImages);
        return mv;
    }


    @RequestMapping("/saveRollingImages")
    @ResponseBody
    public ResponseContent saveRollingImages(HttpServletRequest request) throws IOException {
        String [] rollingImageIds = request.getParameterValues("rollingImageId");
        String [] imageStoreIds = request.getParameterValues("imageStoreId");
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("courseImageFile");
        if(rollingImageService.saveRollingImages(rollingImageIds, imageStoreIds, files)){
            return ResponseContent.buildSuccess("保存成功");
        }else {
            return ResponseContent.buildSuccess("保存失败");
        }
    }

    @RequestMapping("/v1/getRollingImageList")
    @ResponseBody
    public ResponseContent<List<String>> getRollingImageList() {
        List<RollingImage> rollingImages = rollingImageService.getRollingImageList();
        List<String> list = new ArrayList<>();
        for(RollingImage rollingImage : rollingImages){
            if(Preconditions.isNotBlank(rollingImage.getImageStore())){
                list.add(String.format(imageUrl, rollingImage.getImageStore().getId()));
            }
        }
        return ResponseContent.buildSuccess(null, list);
    }
}